<?php

//Must do: check times login
//Test https....
//CSRF
//Draw workflow....
class Index extends Admin_Controller {

    public function __construct() {
        parent::__construct();

        $this->_load();
    }

    public function index() {
        $this->_replacePhrase();
    }

    public function add() {
        if (!(bool) $this->input->is_ajax_request()) {
            redirect('product/admincp/index');
            return false;
        }

        $aConfig = $this->_getRuleProduct();
        $this->load->library('form_validation', null, 'validation');
        $this->validation->set_rules($aConfig);
        $this->validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->validation->run() === false) {
            $this->return_fail_json($this->_getValidationError());
            return false;
        }

        if ((bool) $aProduct = $this->input->post('product')) {
            if ((bool) $aProduct = $this->product->add($aProduct)) {
                $this->return_success_json($aProduct, $this->lang->line("phrase var='product.add_new_product_successfully'"));
                return true;
            }
        }

        return false;
    }

    private function _load() {
        $this->load->library('pagination');
        $this->load->helper(array('url', 'form'));
        $this->load->model(array('user', 'product'));
        $this->lang->load('admin/general', $this->_slang_name);
        $this->lang->load('admin/product', $this->_slang_name);
    }

    private function _replacePhrase() {
        $this->_adata['token'] = (object) array("name" => $this->security->get_csrf_token_name(), "value" => $this->security->get_csrf_hash());
        $this->fill_phrase('product', $this->_adata, $this->lang->language);
    }

    private function _getRuleProduct() {
        return array(
            array(
                'field' => 'product[name]',
                'label' => $this->lang->line("pharse var='product.name_product'"),
                'rules' => 'trim|required|min_length[5]'
            ),
            array(
                'field' => 'product[order]',
                'label' => $this->lang->line("pharse var='product.order'"),
                'rules' => 'trim|numeric|greater_than[0]'
            ),
            array(
                'field' => 'product[source]',
                'label' => $this->lang->line("pharse var='product.source'"),
                'rules' => 'trim|required|regex_match[#^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)?#i]'
            ),
            array(
                'field' => 'product[level]',
                'label' => $this->lang->line("pharse var='product.level'"),
                'rules' => 'trim|required|numeric|greater_than[0]|less_than[4]'
            ),
            array(
                'field' => 'product[language]',
                'label' => $this->lang->line("pharse var='product.language'"),
                'rules' => 'trim|required|numeric|greater_than[0]|less_than[3]'
            ),
            array(
                'field' => 'product[image]',
                'label' => $this->lang->line("pharse var='product.image'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[is_actived]',
                'label' => $this->lang->line("pharse var='product.status'"),
                'rules' => 'trim|required|numeric|greater_than[-1]|less_than[2]'
            ),
            array(
                'field' => 'product[is_featured]',
                'label' => $this->lang->line("pharse var='product.featured'"),
                'rules' => 'trim|required|numeric|greater_than[-1]|less_than[2]'
            ),
            array(
                'field' => 'product[summary]',
                'label' => $this->lang->line("pharse var='product.summary'"),
                'rules' => 'trim|required|min_length[20]'
            ),
            array(
                'field' => 'product[description]',
                'label' => $this->lang->line("pharse var='product.description'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_title]',
                'label' => $this->lang->line("pharse var='product.meta_title'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_keyword]',
                'label' => $this->lang->line("pharse var='product.meta_keyword'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_description]',
                'label' => $this->lang->line("pharse var='product.meta_description'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_robot]',
                'label' => $this->lang->line("pharse var='product.meta_robot'"),
                'rules' => 'trim|required'
            )
        );
    }

    public function uploadImage() {
        $aConfig = array(
            'encrypt_name' => true,
            'upload_path' => APPPATH . 'static/images/product/',
            'allowed_types' => 'jpeg|jpg|png|bmp',
        );

        $this->load->library('upload', $aConfig);

        if ($this->upload->do_upload('product_image')) {
            if ((bool) $aData = $this->upload->data()) {
                $aImage = $this->product->addImage($aData['file_name']);
                $aConfigImage = array(
                    'source_image' => APPPATH . 'static/images/product/' . $aData['file_name'],
                    //'create_thumb' => TRUE,
                    'maintain_ratio' => TRUE,
                    'width' => 150,
                    'height' => 150,
                    'new_image' => APPPATH . 'static/images/product/thumb/' . $aData['file_name']
                );

                $this->load->library('image_lib', $aConfigImage);

                if ($this->image_lib->resize()) {
                    ///Create obsolute_path_new_image to get link to file image for showing after finish upload
                    //Reason: relative path image, when append image, it not show.
                    $aData += array('obsolute_path_new_image' => base_url() . '/' . $aConfigImage['new_image']);
                    return $this->return_success_json($aConfigImage + $aData, '');
                }

                return $this->return_fail_json($config, $this->image_lib->display_errors('<div class="error">', '</div>'));
            }
        }

        return $this->return_fail_json($aConfig, $this->upload->display_errors('<div class="error">', '</div>'));
    }

    private function _getValidationError() {
        $aField = array('name', 'order', 'level', 'language', 'status',
            'featured', 'notify', 'description', 'summary', 'meta_title', 'meta_keyword',
            'meta_description', 'meta_robot', 'image', 'source');
        $aValidationError = array();

        foreach ($aField as $field) {
            $aValidationError = array_merge($aValidationError, array("{$field}" => form_error("product[{$field}]")));
        }

        return $aValidationError;
    }

    public function getListPages($offset = null) {
        if (!(bool) $this->input->is_ajax_request()) {
            return false;
        }

        $aConfig = $this->getConfigPage();
        $this->pagination->initialize($aConfig);
        $this->_adata['pages'] = $this->pagination->create_links();

        $this->return_success_json($this->_adata['pages'], '', empty($offset) ? 1 : $offset);
    }

    public function getTotalProduct() {
        return $this->product->countProduct();
    }

    public function getConfigPage() {
        return array(
            'base_url' => site_url('product/admincp/index/getListPages'),
            'per_page' => $this->config->item('per_page'),
            'uri_segment' => 5,
            'num_links' => 6,
            'total_rows' => $this->getTotalProduct(),
            'cur_tag_open' => '<strong id="current_page_product" class="current-page">',
            'cur_tag_close' => '</strong>',
//            'num_tag_open' => '<li class="page">',
//            'num_tag_close' => '</li>',
            'use_page_numbers' => true,
            'next_link' => '»',
            'prev_link' => '«',
//            'prev_tag_open' => '<li>',
//            'prev_tag_close' => '</li>',
//            'first_tag_open' => '<li>',
//            'first_tag_close' => '</li>',
//            'last_tag_open' => '<li>',
//            'last_tag_close' => '</li>',
//            'last_link' => 'Last',
//            'first_link' => 'First',
//            'next_tag_open' => '<li>',
//            'next_tag_close' => '</li>',
//            'previous_tag_open' => '<li>',
//            'previous_tag_close' => '</li>'
        );
    }

    public function getList($offset = null) {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        if(!$offset){
            $this->return_fail_json(null, 'offset is empty');
        }
        
        $aProduct = $this->product->getListAdmin($offset);

        $this->return_success_json($aProduct, '');
    }
    
    public function delete(){
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $aIds = $this->input->post('product_ids');
        $aIds = (array)json_decode($aIds);
        if((bool)$this->product->delete($aIds)){
            $this->return_success_json(NULL, '');
            
            return true;
        }
        
        $this->return_fail_json(NULL, '');
    }
}
?>

